package com.itheima.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.pojo.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisUtil jedisUtil;

    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo) {
        String token = orderInfoVo.getToken();
        if (token == null) {
            return Result.error("非法访问");
        }

        long delete = jedisUtil.delete(token);
        if (delete==0L) {
            return Result.error("非法访问，请刷新页面");
        }
        //核对验证码
        String validateCode = orderInfoVo.getValidateCode();
        String code = jedisUtil.get(orderInfoVo.getTelephone() + RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCode == null || !validateCode.equals(code)) {
            return Result.error("验证码错误");
        }
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
        try {
            return orderService.submit(orderInfoVo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Map map = orderService.findById4Detail(id);
        return Result.success("", map);
    }

    @RequestMapping("/getToken")
    public Result getToken() {
        String uuid = String.valueOf(UUID.randomUUID());
        jedisUtil.addTimeLimited(uuid, 1200, uuid);
        return Result.success("", uuid);
    }
}
